<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 输入框 -->

      <el-row :gutter="5">
        <el-col :span="7"
          ><el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addUserDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="mg_stateChange(scope)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="changeUserDialog(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
            ></el-button>
            <el-tooltip content="分配权限" placement="top"
              ><el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.toatal"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      @close="addClose"
      title="添加用户"
      :visible.sync="addUserDialog"
      width="50%"
    >
      <span>
        <el-form
          :model="addUserList"
          ref="addUserRef"
          label-width="70px"
          :rules="addUserRuls"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserList.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserList.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserList.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserList.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="changeUserVisible"
      width="50%"
      @close="closeChange"
    >
      <span>
        <el-form
          ref="changeUserRef"
          :model="changeUserValue"
          label-width="70px"
          :rules="changeUserRules"
        >
            <el-form-item  label="用户名" prop="username">
              <el-input disabled v-model="changeUserValue.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="changeUserValue.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="changeUserValue.mobile"></el-input>
            </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regPhone = /^[1][3,4,5,7,8][0-9]{9}$/
      if (regPhone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 1,
      },
      userList: [],
      toatal: 0,
      addUserDialog: false,
      addUserRef: {
        username: '',
      },
      changeUserRef:{},
      changeUserRules:{
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      addUserRuls: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 10,
            message: '密码长度在 6 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      addUserList: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      changeUserVisible: false,
      changeUserValue: {
        username: '',
        email: '',
        mobile: '',
        id:0
      },
     
    }
  },
  methods: {
    async getUserList() {
      await this.$http.get('users', { params: this.queryInfo }).then((res) => {
        // console.log('用户列表数据', res)
        if (res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg)
        } else {
          this.userList = res.data.data.users
          // console.log('用户列表数据', res.data.data)
          this.toatal = res.data.data.total
          this.$message.success('获取用户数据成功！')
        }
      })
    },
    changeUserDialog(id) {
      this.changeUserVisible = true
      this.changeUserValue.username=id.username
      this.changeUserValue.email=id.email
      this.changeUserValue.mobile=id.mobile
      this.changeUserValue.id=id.id
      console.log('插槽参数', id)
    },
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async mg_stateChange(tap) {
      await this.$http
        .put(`users/${tap.id}/state/${tap.mg_state}`)
        .then((res) => {
          if (res.data.meta.status !== 200) {
            tap.mg_state = !tap.mg_state
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message.success('更新用户状态成功！')
          }
        })
    },
    addUser() {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return
        await this.$http.post('users', this.addUserList).then((res) => {
          if (res.data.meta.status !== 201)
            return this.$message.error(res.data.meta.msg)
          this.$message.success('添加用户成功！')
          this.addUserDialog = false
          this.getUserList()
        })
      })
    },
    changeUser(){
        this.$refs.changeUserRef.validate(async valid=>{
          if(!valid) return
          await this.$http.put('users/'+this.changeUserValue.id,this.changeUserValue).then(res=>{
            if(res.data.meta.status!==200) return this.$message.error(res.data.meta.msg)
            this.$message.success('修改用户信息成功！')
            this.changeUserVisible=false
            this.getUserList()
          })
        }) 
      },
          //删除用户
    delUser(id){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async () => {
         await this.$http.delete('users/'+id).then(res=>{
            if(res.data.meta.status!==200) return this.message.error(res.data.meta.msg)
            this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //监听添加对话框关闭事件
    addClose() {
      this.$refs.addUserRef.resetFields()
    },
    closeChange(){
      this.$refs.changeUserRef.resetFields()
    }
  },
  created() {
    this.getUserList()
  },
}
</script>

<style lang="less" scoped>
</style>